<?php
// no direct access

defined('_JEXEC') or die;

$session_vipcard =& JFactory::getSession();
$session_vipcard_id =  $session_vipcard->getId();

$lang =& JFactory::getLanguage();

$page_heading = JText::_(WrdHelper::stringURLSafeAliasLang('WRD_PROMOTION_CATEGORY_'.$this->category_detail->title));
$title = JText::_('WMCVIP_TITLE_PREFIX').$page_heading.JText::_('WMCVIP_TITLE_SUFIX');
$document = &JFactory::getDocument();
$document->setTitle($title) ;

?>

<script src="<?php echo JURI::base(); ?>js/number_format.js"></script>

<h4>
    <?php echo $page_heading; ?>
</h4>



<script type="text/javascript">
    jQuery('.btn').button();
    
    var scItems = [];
	var currentUserPoint = "<?php echo $this->userPoint; ?>";    
    var totalPointSubtract = currentUserPoint;
	
    if(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>") != ""){
        var data_dec = decodeCookies(jQuery.cookie("<?php echo md5($session_vipcard_id); ?>"));
        scItems = json_decode(data_dec);
    }
    
    jQuery(function(){
        //initShoppingCart();
        totalPointAndCash();        

        jQuery(".add-to-cart a").click(function(index){
            var objName = jQuery(this).attr("name");
            var item = {
                id:     0,
                qty:    0,
                pcode:  0,
                type:   1,
                img:    '',
                point:  0,
                pointx: 0,
                cash:   0,
                name:   '',
				ptotal:  1
            };
            
            params = objName.split("_");            
            item.id = params[1];
            var inputName = jQuery("input[name="+objName+"_type]:checked").attr("id");
            item.type = jQuery("#"+inputName).val();
           
            if(jQuery("input[name="+objName+"_type]:checked").length == 0){
                jQuery('#error_message').html('<p><?php echo JText::_('WRD_PROMOTION_PLEASE_CHOOSE_RWWRD_PROMOTION_EDEMPTION_TYPE') ?></p>');
                jQuery('#errorModal').modal('show');
                return false;
            }
            else {
                var qty = jQuery("input[name="+inputName+"_qty]").val();
               
                jQuery("input[name="+inputName+"_qty]").val(parseInt(qty)+1);
                var productPoint = 0;
                if(item.type == 1) {
                    item.point = jQuery("#"+inputName+"_point").val();  
                    item.cash = 0;
                    item.pointx = 0;
                    productPoint = (parseInt(qty)*parseInt(item.point));
                }
                else {
                    item.point = 0;
                    item.pointx = jQuery("#"+inputName+"_pointx").val();
                    item.cash = jQuery("#"+inputName+"_cash").val();  
                    productPoint = (parseInt(qty)*parseInt(item.pointx));  
                }
                
                if(qty <= 0){
                    
                    jQuery('#error_message').html('<p>Please input a valid value!</p>');
                    jQuery('#errorModal').modal('show');
                
                    jQuery("input[name="+inputName+"_qty]").focus();
                    return false;
                }
                else {
                    var subtractPoint = 0;
                    if(scItems != null && scItems.length > 0){
                        for(var i=0; i<scItems.length; i++){
                            if(item.id == scItems[i].id){
                               	
                                totalPointSubtract = parseInt(totalPointSubtract) + (parseInt(scItems[i].qty)*parseInt(scItems[i].type == 1 ? scItems[i].point : scItems[i].pointx));
                            }
                        }
                    }
                    
                    var subtractPoint = totalPointSubtract;
                    subtractPoint = parseInt(subtractPoint) - parseInt(productPoint);
                        
                    if(subtractPoint < 0){
                        jQuery('#error_message').html('<p><?php echo JText::_('WRD_PROMOTION_YOUR_POINT_IS') ?> "+(totalPointSubtract)+" < " + productPoint+" <?php echo JText::_('WRD_PROMOTION_IS_NOT_ENOUGHT_TO_REDEEM') ?></p>');
                        jQuery('#errorModal').modal('show');
                        
                        
                    }
                    else {
						var update = true;
						var ptotal = 0;
						
                        item.qty = parseInt(qty);
                        item.img = jQuery("#"+objName+"_img").attr("src");
                        item.pcode = jQuery("#"+objName+"_code").html();
                        nameItem = jQuery("#item_"+item.id+"_name").val();
                        item.name = objName;
                        
                        
                        if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                
                                if(scItems[i].id == item.id) {
                                   
                                    if(scItems[i].type != item.type) {
                                       update = false;
                                    }else{
                                        item.qty = parseInt(scItems[i].qty) + 1;
                                        scItems[i] = item;
                                        update = true;
                                        break;
                                    }
                                   
                                }else{
                                    update = false;
                                }
                            }
                            
                            if(update == false) {
                               
                                scItems.push(item);
                                                            
                            }
                        }
                        else {
                            if(scItems ==  null){
                                scItems = new Array();
                                scItems[0] = item;
                            } else {
                                scItems.push(item);    
                            }
                            
                        }
 
                    }
                }

            }
			
			for(var i=0; i<scItems.length; i++){
                if(scItems[i].id == item.id) {
                    ptotal = parseInt(ptotal) + parseInt(scItems[i].qty);
                }
            }
			item.ptotal = ptotal;
            var page_refresh = false;
            /*** Process Data ***/
            jQuery.ajax({
				async: false,
                type: "post",
                url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&layout=addtocart&view=redemptions'); ?>",
                data: "params="+json_encode(item),
                success: function(json){
                    var result = eval(json);
                    
                    if (result.success == true)
                    {
                        totalPointAndCash();
                        
                        jQuery('#cartModal').modal('toggle').on('shown.bs.modal', function (e) {
                            myModal = jQuery('#cartModal');
                            clearTimeout(myModal.data('hideInteval'))
                            var id = setTimeout(function(){
                                myModal.modal('hide');
                            },1000);
                            myModal.data('hideInteval', id);
                        });
                    }
                    else
                    {
						if(result.refresh == true) page_refresh = true;
                    	item.qty = result.max;
                    	
                    	if(scItems != null && scItems.length > 0){
                            for(var i=0; i<scItems.length; i++){
                                if(scItems[i].id == item.id) {
                                    if(scItems[i].type == item.type){
                                        item.qty =  parseInt(result.allow);
                                        if(item.qty <= 0){
                                            scItems.splice(i,1);
                                        }
                                    }
                                }
                            }

                        }
 
						totalPointAndCash();
						if(result.html != ''){
							jQuery('#error_message').html('<p>'+result.html+'</p>');
							jQuery('#errorModal').modal('show');
						}
                        
                    }
                }
                
            }); 
            
			var data_enc = encodeCookies(scItems);
			jQuery.cookie("<?php echo md5($session_vipcard_id); ?>", json_encode(data_enc), { expires: 1, path: '/' });   
            
            if(page_refresh == true){
            	location.reload(true);
            }
			
            return false;
        });
        
    });
    
	function encodeCookies(obj){
		var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=encryptcart'); ?>",
            data: "params="+json_encode(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('security hole');
                }
            }
        });
        
        return data;
    }
	
    function decodeCookies(obj){
    	var data ;
    	jQuery.ajax({
    		async: false,
            type: "post",
            url : "<?php echo utilitiesProvider::rewriteGlobalUrl('index.php?option=com_promotions&task=decryptcart'); ?>",
            data: "params="+(obj),
            success: function(json){ 
                var result = eval(json);
                
                if (result.success == true)
                {
                	data =  result.data;
                }
                else
                {
                	//console.log('can not decrypt');
                }
            }
        });
        return data;
    }
    
    function totalPointAndCash(){
        var totalPoint = 0;
        var totalCash = 0;
        
        if(scItems != null && scItems.length > 0){
           // console.log(scItems);
        	var total_item = 0;
            for(var i=0; i<scItems.length; i++){
                totalPoint = parseInt(totalPoint) + parseInt(scItems[i].point)*parseInt(scItems[i].qty) + parseInt(scItems[i].pointx)*parseInt(scItems[i].qty);
                totalCash = parseInt(totalCash) + parseInt(scItems[i].cash)*parseInt(scItems[i].qty); 
                total_item = total_item + parseInt(scItems[i].qty);
                
                //console.log(parseInt(scItems[i].qty));
            }
            
            totalPointSubtract = parseInt(currentUserPoint) - parseInt(totalPoint);
            //console.log('total:'+total_item);
            
            jQuery(".cart-detail").show();
            jQuery(".navbar-right .fa-shopping-cart").html('<span class="badge badge-num">'+total_item+'</span>');
            
        }
        else{
            jQuery(".cart-detail").hide();
		}
    }

</script>
<?php
if (count($this->items) > 0) :
?>

    <form role="form" class="custom" action="<?php echo JRoute::_("index.php?option=com_promotions&view=redemptions")?>" method="post" name="adminForm" >
    <?php 
        foreach($this->items as $id => $item) : 
        	$item->name = unserialize($item->name);
        	$item->name = $item->name[$lang->getTag()];
        	
        	$item->des = unserialize($item->des);
        	$item->des = $item->des[$lang->getTag()];
        	
            $images = '';
            if($item->image != ''):
                $images = '<img id="item_'.$item->id.'_img" class="thumb-img" alt="'.$item->name.'" title="'.$item->name.'" src="'.JURI::base().'wrd/image2/'.$item->image.'" />';
            else:
                $images = '';
            endif;
            
            $show = false;
            if($item->cash > 0):
                $show = true;    
            endif;
            ?>
                <div class="panel panel-default item-details panel-point-wmc">
                    <div class="panel-heading panel-heading-img">
                        <a href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&layout=details&id='.$item->id.'&Itemid=174'); ?>">
                          <img class="item_detail_image lazy img-responsive" 
                          id="item_<?php echo $item->id ?>_img" 
                          alt="<?php echo $item->name ?>" 
                          title="<?php echo $item->name ?>" 
                          src="<?php echo JURI::base().'wrd/image2/'.$item->image; ?>">
                        </a>
                    </div>
                    <div class="panel-body">
                            	<div class="image_section">
            	                	<div class="silde">
            	                	    
            							<div class="mosaic-overlay">
            								<div class="stop">
            									<div class="stop_content" >
            									    <h4>
            									        <a href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&layout=details&id='.$item->id.'&Itemid=174'); ?>">
            									            <?php echo $item->name; ?></a>
            									    </h4>    
            									</div>
            								</div>
            								<br clear="all">
            								<!-- <div class="sbottom">
            									<div class="des"><?php echo mb_substr(strip_tags($item->des), 0,20,'utf-8').'...' ; ?></div>
            									<br clear="all">
            									<div class="view_more"><a href="<?php echo JRoute::_('index.php?option=com_promotions&view=redemptions&layout=details&id='.$item->id.'&Itemid=174'); ?>"><?php echo JText::_('WRD_PROMOTION_VIEW_MORE'); ?></a></div>
            								</div> -->
            							</div>
            							
            					    </div>
            				    </div>
            				    <div class="point_to_exchange">
            				    	<?php if($show == true): ?>
            						<label class="btn btn-default btn-block btn-fltlft" for="item_<?php echo $item->id; ?>_id_2"  >
            				    		<input 
            				    		<?php echo $item->point <= 0 ? 'checked' : ''; ?>
            				    		name="item_<?php echo $item->id; ?>_type" type="radio" id="item_<?php echo $item->id; ?>_id_2" value="2">
            				    		<?php echo number_format($item->pointx,0,'.',','); ?> 
            				    		<?php echo JText::_('WRD_PROMOTION_POINTS'); ?> + 
            				    		<?php echo number_format($item->cash,0,'.',','); ?> 
            				    		<?php echo JText::_('WRD_PROMOTION_VND'); ?>
            				    	</label>
            						<input type="hidden" name="item_<?php echo $item->id ?>_id_2_qty" value="1" />
                                    <input type="hidden" id="item_<?php echo $item->id ?>_id_2_point" value="<?php echo $item->point ?>" />
                                    <input type="hidden" id="item_<?php echo $item->id ?>_id_2_pointx" value="<?php echo $item->pointx ?>" />
                                    <input type="hidden" id="item_<?php echo $item->id ?>_id_2_cash" value="<?php echo $item->cash ?>" />
                                    <br>
            				    	<?php endif; ?>
            			    	
            			    		<?php if($item->point > 0): ?>
            				    	<label class="btn btn-default btn-block btn-fltlft" for="item_<?php echo $item->id; ?>_id"  >
            				    		<input 
            				    		checked="checked" 
            				    		name="item_<?php echo $item->id; ?>_type" 
            				    		type="radio" 
            				    		id="item_<?php echo $item->id; ?>_id" value="1">
            				    		<?php echo number_format($item->point,0,'.',','); ?> 
            				    		<?php echo JText::_('WRD_PROMOTION_POINTS'); ?>
            				    	</label>
            				    	<input type="hidden" name="item_<?php echo $item->id; ?>_id_qty" value="1" />
            						<input type="hidden" id="item_<?php echo $item->id ?>_id_point" value="<?php echo $item->point ?>" />
            						<input type="hidden" id="item_<?php echo $item->id ?>_id_pointx" value="<?php echo $item->pointx ?>" />
            						<input type="hidden" id="item_<?php echo $item->id ?>_id_cash" value="<?php echo $item->cash ?>" />
            				    	<?php endif; ?>
            				    	
            				    </div>
            				    
            				    <div class="true_price pull-right help-block">
            						<label>(<?php echo JText::_('WRD_PROMOTION_VALUE') ?> 
            						<?php echo number_format($item->price,0,'.',','); ?> 
            						<?php echo JText::_('WRD_PROMOTION_VND'); ?>)</label>
             					</div>
            					
                    </div>
                    <div class="panel-heading">
                        <?php if($item->quantity == 0): ?>
                                    <div class="fright pull-right" style="float: right; color: red;"><b><i>(<?php echo JText::_('WRD_PROMOTION_OUT_OF_STOCK'); ?>)</i></b></div>
                                <?php else: ?>
                                    <?php if($this->user->id == 0): ?>
                                    <div class="add-to-cart-login pull-right">
                                        <a class="need_login" name="item_<?php echo $item->id; ?>" href="javascript:void(null);">
                                            <i class="fa fa-shopping-cart"><span class="badge badge-add">+</span></i>
                                        </a></div>
                                    <?php else: ?>
                                        <div class="add-to-cart fright pull-right">
                                            <a name="item_<?php echo $item->id; ?>" href="javascript:void(null);">
                                                <i class="fa fa-shopping-cart"><span class="badge badge-add">+</span></i>
                                            </a></div>
                                    <?php endif;?>
                                <?php endif;?>
                                <br clear="all">
                    </div>
                </div>
          	<?php endforeach; ?>
			<br clear="both">
			<div class="text-center">
			<?php echo $this->pagination->getPagesLinks(); ?>
			</div>
			<?php echo JHTML::_( 'form.token' ); ?>
    </form>

<input type="hidden" id="promotion-link" value="" />
<?php else:?>
	<p class="help-block">Empty</p>
<?php endif; ?>
